package cn.edu.seu.herald.informationplatform.filter;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.edu.seu.herald.informationplatform.dao.database.LeagueUserDao;

public class LeagueSpecified implements Filter {
	
	public static final String PARAM_NAME_OF_LEAGUE_ID = "league";

	@Override
	public void init(FilterConfig config) throws ServletException {}

	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request,
			ServletResponse response, FilterChain chain)
					throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		
		// 获取请求中的社团标识
		String leagueIdParam =
				httpRequest.getParameter(PARAM_NAME_OF_LEAGUE_ID);
		
		if (leagueIdParam == null) {
			httpResponse.sendError(400, "league specified");
			return;
		}
		
		try {
			int leagueId = Integer.valueOf(leagueIdParam);
			LeagueUserDao leagueUserAccess = LeagueUserDao.getDao();
			if (!leagueUserAccess.hasId(leagueId)) {
				httpResponse.sendError(404, "league not exist");
				return;
			}
		} catch (NumberFormatException e) {
			httpResponse.sendError(400, "league id format exception");
		} catch (SQLException e) {
			httpResponse.sendError(400, "SQL exception");
		}
		
		chain.doFilter(request, response);
	}

}
